package com.redbudcloud.common;

import net.coobird.thumbnailator.Thumbnails;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang.ArrayUtils;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by zhxiaotong on 17-12-17.
 */
public class BaseUtil {
    private static String CHAR_ENCODE = "UTF-8";
    public static enum FieldTypes{
        INTEGERTOSTRING,FLOATTOSTRING,STRINGTOINTEGER,STRINGTOFLOAT,STRINGTODATE,STRINGTOTIMESTAMP,
        DATETOSTRINGDATE,DATETOSTIRNGTIME,DATETOSTRINGDATETIME,DATETODATE,TIMESTAMPTODATE,STRINGTOSTRING,
        UNCHANGE,FLOAT,DOUBLE,INTEGER,STRING,BIGINTEGER,BIGINTEGERTOSTRING
    }

    /**
     * 字符串判断是否为空
     *
     * @param obj
     * @return
     */
    public static boolean isNull(String obj) {
        if (obj == null || "".equals(obj)||"null".equals(obj)) {
            return true;
        }
        return false;
    }
    public static boolean isNotNull(String obj) {
        if (obj == null || "".equals(obj)) {
            return false;
        }
        return true;
    }

    public static Date yyyySlashMMSlashDD(Date dateStr) {
        String res = "";
        System.out.println(dateStr.toString());
        if (dateStr == null || "".equals(dateStr)) {
            return dateStr;
        }
        return dateStr;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(currentSchoolYearTerm("1709","1809"));
    }
    /**
     * 读取民族信息
     * @param path
     * @return
     */
    public static List<String> readNationList(String path) {
        List<String> nationList = new ArrayList<String>();
        JSONObject jo = readJsonFile(path);
        JSONArray ja = JSONArray.fromObject(jo.get("race"));
        for (int i=0;i<ja.size();i++) {
            nationList.add(ja.getJSONObject(i).get("value").toString());
        }
        return nationList;
    }

    /**
     * 将temp路径的文件复制到正确文件夹下
     * @param file
     * @param dest
     */
    public static void moveFile( String dest ,File file) {
        File destDir = new File(dest);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        System.out.println(file.getName());
        try {
            InputStream input = null;
            BufferedOutputStream bos = null;
            byte[] buffer = new byte[8192];
            int length = -1;
            File destFile = new File(dest, file.getName());
            input = new FileInputStream(file);
            bos = new BufferedOutputStream(new FileOutputStream(destFile));
            while (true) {
                length = input.read(buffer);
                if (length == -1) break;
                bos.write(buffer, 0, length);
            }
            bos.close();
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //递归解压一层压缩包
    public static Map<String, String> importZip(File zipfile, String dest) throws Exception {
        long startTs = Calendar.getInstance().getTimeInMillis();
        Map<String, String> pathMap = new HashMap<String, String>();
        try {
            ZipFile zip = new ZipFile(zipfile, "GBK");
            Enumeration en = zip.getEntries();
            byte[] buffer = new byte[8192];
            String[] folders = {"身份证照片/", "身份证正面/", "毕业证/", "蓝底电子照片/", "学信证明/", "其他/"};
            int length = -1;
            InputStream input = null;
            BufferedOutputStream bos = null;
            File file = null;
            ZipEntry entry = null;
            int folderNum = 0;
            int excelNum = 0;
            while (en.hasMoreElements()) {
                entry = (ZipEntry) en.nextElement();
                if (entry.isDirectory()) {
                    String folder = entry.getName();
                    if (ArrayUtils.contains(folders, folder)) {
                        folderNum++;
                        pathMap.put(folder, dest + File.separator + folder);
                        file = new File(dest, entry.getName());
                        file.mkdir();
                        continue;
                    } else {
                        throw new Exception("压缩包中存在不符合导入规范的文件夹，请检查。");
                    }

                }
                String name = entry.getName();
                //允许所有格式的文件
                /*if (name.indexOf("/")>-1) {
                    String expandName = getExtendName(name);
                    if (!".jpg".equals(expandName.toLowerCase())) {
                        throw new Exception("压缩包中存在不符合扩展名要求的图片文件，请检查。");
                    }
                }*/
                String expandName = getExtendName(name);
                if ((".xls".equals(expandName) || ".xlsx".equals(expandName))&&name.indexOf("/")<0) {
                    pathMap.put("excel", dest + File.separator + name);
                    excelNum++;
                }
                input = zip.getInputStream(entry);
                file = new File(dest, entry.getName());
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                bos = new BufferedOutputStream(new FileOutputStream(file));
                while (true) {
                    length = input.read(buffer);
                    if (length == -1) break;
                    bos.write(buffer, 0, length);
                }
                bos.close();
                input.close();
            }
            if (folderNum!=6) {
                throw new IOException("文件夹数目与规范不匹配，请核对后再上传。");
            }
            if (excelNum!=1) {
                throw new IOException("压缩包内有多个Excel文件，无法识别正确的数据文件，请删除后再上传。");
            }
            zip.close();
        } catch (IOException e) {
            deleteDirectory(dest);
            throw new IOException(e.getMessage());
        }
        long endTs = Calendar.getInstance().getTimeInMillis();
        System.out.println((endTs - startTs) / 1000);
        return pathMap;
    }

    /**
     * 压缩文件夹
     * @param path
     * @param zipFile
     */
    public static void exportZip(String path,File zipFile) {
        long startTm = Calendar.getInstance().getTimeInMillis();
        File srcdir = new File(path);
        if (!srcdir.exists()){
            throw new RuntimeException(path + "不存在！");
        }
        Project prj = new Project();
        Zip zip = new Zip();
        zip.setProject(prj);
        zip.setDestFile(zipFile);
        FileSet fileSet = new FileSet();
        fileSet.setProject(prj);
        fileSet.setDir(srcdir);
        zip.addFileset(fileSet);
        zip.setEncoding("GBK");
        zip.execute();
        long endTm = Calendar.getInstance().getTimeInMillis();
        System.out.println("耗时：" + (endTm - startTm));
    }

    /**
     * 按路径解压缩文件夹,支持多层压缩目录
     * @param zipFilepath
     * @param destDir
     * @throws BuildException
     * @throws RuntimeException
     */
    public static void unzip(String zipFilepath, String destDir)
            throws  RuntimeException {
        if (!new File(zipFilepath).exists())
            throw new RuntimeException("zip file " + zipFilepath
                    + " does not exist.");

        File zipFile = new File(zipFilepath);
        //如果文件路径不是zip文件
        if (".zip".equals(getExtendName(zipFile.getName()))) {
            Project proj = new Project();
            Expand expand = new Expand();
            expand.setProject(proj);
            expand.setTaskType("unzip");
            expand.setTaskName("unzip");
            expand.setEncoding("GBK");

            expand.setSrc(new File(zipFilepath));
            expand.setDest(new File(destDir));
            expand.execute();

            deleteFile(zipFile);
            File tmp = new File(destDir);
            if (tmp.isDirectory()) {
                File[] files = tmp.listFiles();
                for (File f:files
                        ) {
                    if (f.isDirectory()) {
                        File[] f1 = f.listFiles();
                        if (f1==null) {
                            throw new RuntimeException("zip file " + zipFilepath
                                    + " does not exist.");
                        }
                        for (File f2 : f1
                                ) {
                            if (f2.getName().endsWith("zip")) {
                                unzip(f2.getPath(), f2.getAbsolutePath().substring(0, f2.getAbsolutePath().indexOf("zip") - 1));
                            }
                        }
                    }else{
                        if (f.getName().endsWith("zip")) {
                            unzip(f.getPath(), f.getAbsolutePath().substring(0, f.getAbsolutePath().indexOf("zip") - 1));
                        }
                    }
                }
            }

        } else {
            throw new RuntimeException("路径 " + zipFilepath
                    + "不是zip文件 ");
        }
    }

    /**
     * 获取资料文件
     * @param cowList
     * @param path
     * @param fileTypes .xls .zip .jpg ...
     */
    public static void getFilesFromDirectory(CopyOnWriteArrayList<File> cowList, String path, List<String> fileTypes) {
        if (fileTypes==null||fileTypes.size()==0) {
            getFilesFromDirectory(cowList,path);
        } else {
            File f = new File(path);
            if (f.isDirectory()) {
                File[] f1 = f.listFiles();
                for (File f2 : f1) {
                    if (f2.isDirectory()) {
                        getFilesFromDirectory(cowList, f2.getAbsolutePath(), fileTypes);
                    } else {
                        if (fileTypes.contains(getExtendName(f2.getName()))) {
                            cowList.add(f2);
                        }
                    }
                }
            } else {
                if (fileTypes.contains(getExtendName(f.getName()))) {
                    cowList.add(f);
                }
            }
        }
    }

    /**
     *
     * @param cowList
     * @param path
     */
    public static void getFilesFromDirectory(CopyOnWriteArrayList<File> cowList,String path) {
        File f = new File(path);
        if (f.isDirectory()) {
            File[] f1 = f.listFiles();
            if (f1 == null) throw new AssertionError(f.getName()+"不是目录");
            for (File f2:f1) {
                if (f2.isDirectory()) {
                    getFilesFromDirectory(cowList,f2.getAbsolutePath());
                } else {
                    cowList.add(f2);
                }
            }
        } else {
            cowList.add(f);
        }
    }

    /**
     * 文件大小比较
     * @param file
     * @param size 文件大小数组 0 最大KB 1 最小值KB
     * @return
     */
    public static  boolean compareLimitFileSize(File file , int ... size) {
        int maxSize = size[0],minSize = 0;
        if (size.length>1) {
            minSize = size[1];
        }
        return file.length()<(1024*maxSize)&&file.length()>(1024*minSize);
    }

    public static Date dateToStr(java.util.Date dateDate) throws ParseException {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateDate);
        cal.getTime();
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy/MM/dd");
        Date date = formatter1.parse(dateDate.toString());
        return date;
    }

    /**
     * 日期字符串
     * @return
     */
    public static String nowDateToStr() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMddHHmm");
        String str = formatter1.format(cal.getTime());
        return str;
    }



    /**
     * 调整图片的大小（宽高等比）
     *
     * @param input
     * @param targetW 宽
     * @param targetH 高
     * @return
     * @throws Exception
     */
    public synchronized static void resize(File input, File smallFile,
                                           int targetW, int targetH) throws Exception {
        Thumbnails.of(input).size(targetW, targetH).toFile(smallFile);
    }

    /**
     * 原图压缩
     *
     * @param input
     * @param smallFile
     * @throws Exception
     */
    public synchronized static void resize(File input, File smallFile) throws Exception {
        //图片尺寸不变，压缩图片文件大小outputQuality实现,参数1为最高质量
        Thumbnails.of(input).scale(1f).outputQuality(0.25f).toFile(smallFile);
    }




    /**
     * 通过反射设置值
     *
     * @param bean
     * @param key
     * @param v
     */
    public static void invokeSetterMethod(Object bean, String key, Object v) {
        Class c = bean.getClass();
        try {
            Field f = c.getDeclaredField(key);
            f.setAccessible(true);
            if (v != null) {
                try {
                    f.set(bean, v);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }

    }


    public static Object invokeMethod(Object newBean, Object oldBean) throws IntrospectionException, InvocationTargetException {
        Class c = newBean.getClass();
        Field[] fields = c.getDeclaredFields();
        String oldClassName=oldBean.getClass().getSimpleName();
        for (Field f : fields) {
            f.setAccessible(true);
            try {
                Object v = f.get(newBean);
                if (v != null&&!"".equals(v)) {
                    String className=v.getClass().getSimpleName();//字段类型名称
                    if(className=="StudentEnroll"&&"CrawlerStudent".equals(oldClassName)){
                        invokeMethod(newBean,v);//如果是报名信息表就递归调用
                    }else{
                        PropertyDescriptor pd = new PropertyDescriptor(f.getName(), oldBean.getClass());
                        if(pd!=null&&!"studentEnroll".equals(f.getName())){
                            Method wM = pd.getWriteMethod();//获得写方法
                            wM.invoke(oldBean, v);
                        }
                    }
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
        return oldBean;

    }

    /**
     * 写入properties信息
     *
     * @param filePath       绝对路径（包括文件名和后缀名）
     * @param parameterName  名称
     * @param parameterValue 值
     */
    public static void writeProperties(String filePath, String parameterName, String parameterValue) {
        Properties props = new Properties();
        try {

            //如果文件不存在，创建一个新的
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }

            InputStream fis = new FileInputStream(filePath);
            // 从输入流中读取属性列表（键和元素对）
            props.load(fis);
            fis.close();
            OutputStream fos = new FileOutputStream(filePath);
            props.setProperty(parameterName, parameterValue);
            // 以适合使用 load 方法加载到 Properties 表中的格式，
            // 将此 Properties 表中的属性列表（键和元素对）写入输出流
            props.store(fos, parameterName);
            fos.close(); // 关闭流
        } catch (IOException e) {

        }
    }


    /**
     * @param filePath properties文件绝对路径（包括文件名和后缀）
     * @param key      属性key
     * @return String 返回value
     * @Title: readValue
     * @Description: TODO  通过绝对路径获取properties文件属性，  根据key读取value
     */
    public static String readValue(String filePath, String key) {
        Properties props = new Properties();
        InputStream in = null;

        try {
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            in = new BufferedInputStream(new FileInputStream(filePath));
            props.load(in);
            String value = props.getProperty(key);
            if (value == null) {
                value = "";
            }
            return value;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                in.close();//-----------------------------------important
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取文件的扩展名
     *
     * @param fileName
     * @return
     */
    public static String getExtendName(String fileName) {
        String extName = "";
        if (fileName.indexOf(".")>-1) {
            Integer num = fileName.lastIndexOf(".");
            extName = fileName.substring(num);
        }
        return extName;
    }

    /**
     * @param str 源字符串转换成字节数组的字符串
     * @return
     */
    public static byte[] StringToByte(String str) {
        return StringToByte(str, CHAR_ENCODE);
    }


    /**
     * UTF-8 一个汉字占三个字节
     *
     * @param str 源字符串
     *            转换成字节数组的字符串
     * @return
     */
    public static byte[] StringToByte(String str, String charEncode) {
        byte[] destObj = null;
        try {
            if (null == str || str.trim().equals("")) {
                destObj = new byte[0];
                return destObj;
            } else {
                destObj = str.getBytes(charEncode);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return destObj;
    }

    /**
     * 删除单个文件
     *
     * @param sPath 被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }


    /**
     * 删除目录（文件夹）以及目录下的文件
     *
     * @param sPath 被删除目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String sPath) {
        //如果sPath不以文件分隔符结尾，自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        //如果dir对应的文件不存在，或者不是一个目录，则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        //删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } //删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }

    // 转化字符串为十六进制编码
    public static String toHexString(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return str;
    }

    // 转化十六进制编码为字符串
    public static String toStringHex(String s) {
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "utf-8");//UTF-16le:Not
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    public static File getFile(String parentPath, String fileName) {
        File parentFile = new File(parentPath);
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        File file = new File(parentFile, fileName);
        //如果存在获取扩展名称然后重新命名
        if (file.exists()) {
            String ext = getExtendName(fileName);
            int n = fileName.indexOf(".");
            fileName = fileName.substring(0, n);
            fileName = fileName + "_" + new Date().getTime() +  ext;
            file = new File(parentFile, fileName);
        }
        return file;
    }

    /**
     * 汉字转换位汉语拼音首字母，英文字符不变
     *
     * @param chines 汉字
     * @return 拼音
     */

    public static String converterToFirstSpell(String chines) {
        String pinyinName = "";
        char[] nameChar = chines.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < nameChar.length; i++) {
            if (nameChar[i] > 128) {
                try {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat);
                    if (temp.length>0) {
                        pinyinName += temp[0].charAt(0);
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                pinyinName += nameChar[i];
            }
        }
        return pinyinName;
    }

    /**
     * 汉字转换位汉语拼音首字母，英文字符不变
     *
     * @param chines 汉字
     * @param area
     * @return 拼音
     */

    public static String converterToFirstSpell(String chines, String area) {
        String pinyinName = "";
        char[] nameChar = chines.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < nameChar.length; i++) {
            if (nameChar[i] > 128) {
                try {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat);
                    if (temp.length>0) {
                        pinyinName += temp[0].charAt(0);
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                pinyinName += nameChar[i];
            }
        }
        if(area != null && !area.equals("")) {
            Map<String, String> map = new HashMap<String, String>(){{
                put("北京", "bj");
                put("上海", "sh");
                put("安徽", "ah");
                put("广东", "gd");
                put("山东", "sd");
                put("四川", "sc");
                put("陕西", "sx");
                put("河南", "hn");
            }};
            if(map.get(area) != null) {
                pinyinName += map.get(area);
            }
        }
        return pinyinName;
    }

    /**
     * 汉字转换位汉语拼音，英文字符不变
     *
     * @param chines 汉字
     * @return 拼音
     */

    public static String converterToSpell(String chines) {
        String pinyinName = "";
        char[] nameChar = chines.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < nameChar.length; i++) {
            if (nameChar[i] > 128) {
                try {
                    pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0];
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinName += nameChar[i];
            }
        }
        return pinyinName;
    }

    /**
     * 通过递归调用删除一个文件夹及下面的所有文件
     * @param file
     */
    public static void deleteFile(File file){
        if(file.isFile()){//表示该文件不是文件夹
            file.delete();
        }else{
            //首先得到当前的路径
            String[] childFilePaths = file.list();
            if(childFilePaths!=null && childFilePaths.length >0){
                for(String childFilePath : childFilePaths){
                    File childFile=new File(file.getAbsolutePath()+File.separator+childFilePath);
                    deleteFile(childFile);
                }
            }
            file.delete();
        }
    }

    public static Integer[][] getIndexArrayByStrArray(String originStr,String[] regs) {
        Integer[][] arr = new Integer[regs.length][];
        for (int i=0;i<regs.length;i++) {
            List<Integer> indexList = new ArrayList<Integer>();
            String str = new String(originStr);
            while (!indexList.contains(indexList.size()>0?indexList.get(indexList.size()-1)+str.indexOf(regs[i])+1:str.indexOf(regs[i]))) {
                if (str.indexOf(regs[i])>-1) {
                    indexList.add(indexList.size()>0?indexList.get(indexList.size()-1)+str.indexOf(regs[i])+1:str.indexOf(regs[i]));
                    str = str.substring(str.indexOf(regs[i])+1);
                } else {
                    break;
                }
            }
            arr[i]= new Integer[indexList.size()];
            indexList.toArray(arr[i]);
        }
        return arr;
    }

    /**
     * 获取Json对象
     * @param Path
     * @return
     */
    public static JSONObject readJsonFile(String Path) {
        BufferedReader reader = null;
        String laststr = "";
        try {
            FileInputStream fileInputStream = new FileInputStream(Path);
            InputStreamReader inputStreamReader = new InputStreamReader(
                    fileInputStream, "utf-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = "";
            while ((tempString = reader.readLine()) != null) {
                laststr += tempString;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        JSONObject jo = JSONObject.fromObject(laststr);
        return jo;
    }

    /**
     * 写JSON文件
     * @param filePath
     * @param sets
     * @return
     */
    public static void writeJsonFile(String filePath,String sets) {
        FileWriter fw = null;
        PrintWriter out = null;
        try {
            fw = new FileWriter(filePath);
            out = new PrintWriter(fw);
            out.write(sets);
            out.println();
            fw.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  判断数组是否具有匹配集合
     * @param roles
     * @param matchRoleId
     * @return
     */
    public static boolean matchRole(JSONArray roles,Integer matchRoleId){
        boolean flag=false;
        for(int i=0;i<roles.size();i++){
            JSONObject role=roles.getJSONObject(i);
            Integer roleId=role.getInt("roleid");
            if(matchRoleId.intValue()==roleId.intValue()){
                flag=true;
            }

        }
        return flag;

    }
    /**
     *  判断字符串里面是否具有匹配集合
     * @param roles
     * @param matchRoleId
     * @return
     */
    public static boolean matchRole(String roles,Integer matchRoleId){
        boolean flag=false;
        String[] rolesArray=roles.split(",");
        for(int i=0;i<rolesArray.length;i++){
            if(!"".equals(rolesArray[i])){
                Integer roleId=Integer.valueOf(rolesArray[i]);
                if(matchRoleId.intValue()==roleId.intValue()){
                    flag=true;
                }
            }

        }
        return flag;
    }

    /**
     *
     * @param enrollBatch
     * @param currentBatch
     * @return
     */
    public static String currentSchoolYearTerm(String enrollBatch,String currentBatch) {
        Integer batch1 = Integer.valueOf(enrollBatch);
        Integer batch2 = Integer.valueOf(currentBatch);
        Integer diff = batch2 - batch1;
        Integer quotient = diff/100;
        Integer remainder = diff%100;
        String schoolYear ;
        switch (quotient) {
            case 0:schoolYear="第一学年";break;
            case 1:schoolYear="第二学年";break;
            case 2:schoolYear="第三学年";break;
            case 3:schoolYear="第四学年";break;
            case 4:schoolYear="第五学年";break;
            default:schoolYear="第一学年";
        }
        String schoolTerm ;
        switch (remainder) {
            case 0:schoolTerm="第一学期";break;
            case 6:schoolTerm="第二学期";break;
            default:schoolTerm="第一学期";break;
        }
        return schoolYear+schoolTerm;
    }

    /**
     * 把sql查询结果转成JSONArray
     *
     * @param keys 数据列的字段名，注意要和sql的顺序一致，一般情况下，student_id会写成studentId，可以为反射做好准备
     * @param types 处理类型，定义见本类enum，FieldTypes
     * @param values 查询结果
     * @return
     */
    public static JSONArray convertSqlResultToJson(String[] keys,FieldTypes[] types,List<Object[]> values) throws ParseException {
        JSONArray ret = null;
        if (keys == null || types == null || values == null){
            return ret;
        }
        if (keys.length != types.length){
            return ret;
        }
        if(values.size() > 0){
            ret = new JSONArray();
            for (int i = 0;i < values.size();i++){
                Object[] o = values.get(i);
                JSONObject jo;
                jo = convertSqlFieldToJson(keys,types,o);
                ret.add(jo);
            }
        }
        return ret;
    }

    public static JSONObject convertSqlFieldToJson(String[] keys,FieldTypes[] types,Object[] values) throws ParseException {
        JSONObject o = new JSONObject();
        for (int i = 0;i < keys.length;i++) {
            String key = keys[i];
            FieldTypes type;
            if(types == null){
                type = FieldTypes.UNCHANGE;
            } else {
                type = types[i];
            }
            SimpleDateFormat sdf = null;
            Object value = values[i];
            Date d = null;
            switch (type) {
                case INTEGERTOSTRING:
                    if (value == null){
                        o.put(key,"");
                    } else {
                        Integer iv = (Integer) value;
                        o.put(key, iv.toString());
                    }
                    break;
                case BIGINTEGERTOSTRING:
                    if (value == null){
                        o.put(key,"");
                    } else{
                        BigInteger iv = (BigInteger) value;
                        o.put(key, iv.toString());
                    }
                    break;
                case FLOATTOSTRING:
                    if (value == null){
                        o.put(key,"");
                    } else {
                        Float fv = (Float) value;
                        o.put(key, fv.toString());
                    }
                    break;
                case DATETOSTIRNGTIME:
                    if (value == null){
                        o.put(key,"");
                    } else {
                        sdf = new SimpleDateFormat("HH:mm:ss");
                        java.sql.Date qtv = (java.sql.Date) value;
                        d = new Date(qtv.getTime());
                        o.put(key, sdf.format(d));
                    }
                    break;
                case DATETOSTRINGDATE:
                    if (value == null){
                        o.put(key,"");
                    } else {
                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                        java.sql.Date qdv = (java.sql.Date) value;
                        d = new Date(qdv.getTime());
                        o.put(key, sdf.format(d));
                    }
                    break;
                case DATETOSTRINGDATETIME:
                    if (value == null){
                        o.put(key,"");
                    } else {
                        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        java.sql.Date qdtv = (java.sql.Date) value;
                        d = new Date(qdtv.getTime());
                        o.put(key, sdf.format(d));
                    }
                    break;
                case STRINGTOTIMESTAMP:
                case STRINGTODATE:
                    if (value == null){
                        o.put(key,null);
                    } else {
                        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String sdv = (String) value;
                        d = sdf.parse(sdv);
                        o.put(key, d);
                    }                    break;
                case STRINGTOFLOAT:
                    if (value == null){
                        o.put(key,null);
                    } else {
                        String sfv = (String) value;
                        o.put(key, new Float(sfv));
                    }
                    break;
                case STRINGTOINTEGER:
                    if (value == null){
                        o.put(key,null);
                    } else {
                        String siv = (String) value;
                        o.put(key, new Integer(siv));
                    }
                    break;
                case DATETODATE:
                    if (value == null){
                        o.put(key,null);
                    } else {
                        java.sql.Date qd = (java.sql.Date) value;
                        d = new Date(qd.getTime());
                        o.put(key, d);
                    }
                    break;
                case TIMESTAMPTODATE:
                    if (value == null){
                        o.put(key,null);
                    } else {
                        java.sql.Timestamp qt = (Timestamp) value;
                        d = new Date(qt.getTime());
                        o.put(key, d);
                    }
                    break;
                case STRINGTOSTRING:
                    if (value == null){
                        o.put(key,"");
                    } else {
                        o.put(key, ((String)value).trim());
                    }
                    break;
                case FLOAT:
                    if (value == null){
                        o.put(key,null);
                    } else {
                        o.put(key,new Float(value.toString()));
                    }
                    break;
                case DOUBLE:
                    if (value == null){
                        o.put(key,null);
                    } else {
                        o.put(key,new Double(value.toString()));
                    }
                    break;
                case INTEGER:
                case BIGINTEGER:
                    if (value == null){
                        o.put(key,null);
                    } else {
                        o.put(key, new Integer(value.toString()));
                    }
                    break;
                case STRING:
                    if (value == null){
                        o.put(key,null);
                    } else {
                        o.put(key,((String) value).trim());
                    }
                    break;
                case UNCHANGE:
                    o.put(key, value);
                    break;
                default:
                    o.put(key, value);
                    break;
            }
        }
        return o;
    }

    public static void appendToFile(String fileName, String content) throws IOException {
        File file = new File(fileName);
        if (!file.exists()){
            file.createNewFile();
        }
        FileWriter writer = null;
        // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
        writer = new FileWriter(fileName, true);
        content = content.trim() + "\r\n";
        writer.write(content);
        if(writer != null){
            writer.close();
        }
    }
}
